import json

file_path = r"C:\pro\IT\Python\flaskPy\src\note.json"


class NoteJsonEditor:
    def __init__(self, file_path=file_path):
        self.file_path = file_path
        self.data = self.load_json()

    # 1️⃣ 读取 JSON
    def load_json(self):
        with open(self.file_path, 'r', encoding='utf-8') as f:
            return json.load(f)

    # 2️⃣ 保存 JSON
    def save_json(self):
        with open(self.file_path, 'w', encoding='utf-8') as f:
            json.dump(self.data, f, ensure_ascii=False, indent=2)

    # 3️⃣ 修改 username
    def set_username(self, username: str):
        self.data['username'] = username

    # 4️⃣ 修改 userpwd
    def set_userpwd(self, userpwd: int):
        self.data['userpwd'] = userpwd

    # 5️⃣ 修改 items 中指定 index 的 text
    def set_item_text(self, index: int, text: str):
        if 0 <= index < len(self.data['items']):
            self.data['items'][index]['text'] = text
        else:
            print(f"items 索引 {index} 越界")

    # 6️⃣ 修改 stars 中指定 index 的值
    def set_star(self, index: int, value: str):
        if 0 <= index < len(self.data['stars']):
            self.data['stars'][index] = value
        else:
            print(f"stars 索引 {index} 越界")

    # 7️⃣ 增加 items
    def add_item(self, text=''):
        self.data['items'].append({'text': text})

    # 8️⃣ 删除 items
    def remove_item(self, index: int):
        if 0 <= index < len(self.data['items']):
            self.data['items'].pop(index)
        else:
            print(f"items 索引 {index} 越界")

    # 9️⃣ 打印当前数据
    def show_data(self):
        print(json.dumps(self.data, ensure_ascii=False, indent=2))

    def getnotejsn(self):
        return json.dumps(self.data, ensure_ascii=False)

    def replace_item_text(self, input):
        self.data['items'] = input


# ===========================
# 示例用法
# ===========================
if __name__ == "__main__":
    editor = NoteJsonEditor()
    print(editor.getnotejsn())
    # print("原始数据：")
    # editor.show_data()
    #
    # # 修改字段
    # editor.set_username('Alice')
    # editor.set_userpwd(1234)
    # editor.set_item_text(0, '这是第一个文本项')
    # editor.add_item('新增文本项')
    # editor.set_star(0, '★')
    # editor.set_star(1, '☆')
    #
    # print("\n修改后的数据：")
    # editor.show_data()
    #
    # # 保存到文件
    # editor.save_json()
    # print("\n已保存修改后的数据到 data.json")
